package com.example.demo.mvp.presenter;

import com.example.demo.mvp.model.IModel;
import com.example.demo.mvp.view.IView;

import java.lang.ref.WeakReference;

public abstract class BasePresenter<V extends IView, M extends IModel> implements IPresenter<V> {
    public M model;
    private WeakReference weakReference;

    /**
     * 持有view 并初始化view中model
     * @param view
     */
    @Override
    public void attachView(V view) {
        weakReference = new WeakReference<>(view);
        if (model == null){
            model = createModel();
        }
    }

    @Override
    public void detchView() {
        if (isDestoryView()){
            weakReference.clear();
            weakReference = null;
        }
        if (model != null){
            model.unSubscription();
            model = null;
        }
    }

    @Override
    public boolean isDestoryView() {
        return weakReference != null && weakReference.get() != null;
    }

    /**
     * 去实现
     * @return
     */
    public abstract M createModel();
}
